package cn.kone.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.kone.mapper.CustomerMapper;
import cn.kone.pojo.domain.Customer;
import cn.kone.remote.api.UaaFeignApi;
import cn.kone.remote.dto.param.LoginDto;
import cn.kone.result.JSONResult;
import cn.kone.service.ICustomerService;
import cn.kone.template.WechatTemplate;
import cn.kone.utils.AssertUtil;
import cn.kone.utils.NameUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;


/**
 * <p>
 * 客户 服务实现类
 * </p>
 *
 * @author yuyu
 * @since 2024-03-24
 */
@Service
@GlobalTransactional(name = "customerRegister&&Login")
public class CustomerServiceImpl extends ServiceImpl<CustomerMapper, Customer> implements ICustomerService {


    //因为不是企业微信无法获取手机号信息,这里是直接写死;
    static final String phone = "13838384888";

    //头像
    @Value("${head-portrait}")
    private String headPortrait;

    @Autowired
    private WechatTemplate wechatTemplate;

    @Autowired
    private UaaFeignApi uaaFeignApi;

    @Override
    public Object getOpenId(String code) {

        //获取openid
        String openId = wechatTemplate.getOpenId(code);
        System.out.println("这是openid:" + openId);

        // 通过 openid 查询数据库中是否已存在对应的司机信息
        Customer one = getOne(new LambdaQueryWrapper<Customer>().eq(Customer::getOpenId, openId));
        // 如果查询结果不为空，表示已经存在相同 openid 的司机信息，如果查询结果不为空，则抛出异常并提供提示信息
        AssertUtil.isNull(one, "不要重复注册");

        //保存乘客信息表
        Customer customer = new Customer();
        long customerId = IdUtil.createSnowflake(0, 0).nextId();
        customer.setId(customerId);
        customer.setPhone(phone);
        customer.setCreateTime(new Date());
        customer.setOpenId(openId);
        customer.setName(NameUtil.getName());
        save(customer);


        //保存登陆表
        LoginDto loginDto = new LoginDto();
        loginDto.setId(customerId);
        loginDto.setType(2);
        loginDto.setAvatar(headPortrait);
        loginDto.setNickName(NameUtil.getName());
        loginDto.setOpenId(openId);
        loginDto.setPhone(phone);

        JSONResult jsonResult = uaaFeignApi.saveLogin(loginDto);
        AssertUtil.isTrue(jsonResult.isSuccess(), "用户注册失败");

        return true;
    }
}
